package com.zaoke.web.dao.food.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;

import com.zaoke.web.bo.food.FoodTag;
import com.zaoke.web.dao.JdbcSupport;
import com.zaoke.web.dao.food.FoodTagsDao;

public class FoodTagsDaoImpl extends JdbcSupport implements FoodTagsDao {

	private static final String TABLE = "`zaoke`.`food_tags`";
	private static final String QUERY_VIEW = "`id`, `food_id`, `tag`, `add_userid`, `add_time`, `lastmod_userid`, `lastmod_time`";

	private List<FoodTag> _query(String sql) {
		List<FoodTag> tags = getTemplateMgr().getReadTp().query(sql,
				new RowMapper<FoodTag>() {

					public FoodTag mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						FoodTag tag = new FoodTag();
						tag.setId(rs.getLong("id"));
						tag.setFoodid(rs.getLong("food_id"));
						tag.setTag(rs.getString("tag"));
						tag.setAddUserid(rs.getLong("add_userid"));
						tag.setAddTime(rs.getDate("add_time"));
						tag.setLastmodUserid(rs.getLong("lastmod_userid"));
						tag.setLastmodTime(rs.getDate("lastmod_time"));
						return tag;
					}
				});
		return tags;
	}

	public List<FoodTag> getTagsByFoodIds(Set<Long> remainings) {
		String sql = "select " + QUERY_VIEW + " from " + TABLE
				+ " where `food_id` in (";
		sql += StringUtils.join(remainings, ",");
		sql += ")";
		return _query(sql);
	}

	public List<FoodTag> getAllTags() {
		String sql = "select " + QUERY_VIEW + " from " + TABLE;
		return _query(sql);
	}

	@Override
	public boolean newTags(List<FoodTag> tags) {
		if (tags == null || tags.size() == 0)
			return false;

		String sql = "insert into " + TABLE;
		sql += "(food_id,tag,add_userid,add_time,lastmod_userid,lastmod_time)";
		sql += " values(?,?,?,now(),?,now())";
		boolean res = true;

		for (FoodTag tag : tags) {
			Object[] params = new Object[] { tag.getFoodid(), tag.getTag(),
					tag.getUserid(), tag.getUserid() };
			res = res & (getTemplateMgr().getWriteTp().update(sql, params) > 0);
		}
		return res;
	}

	@Override
	public boolean updateTags(List<FoodTag> tags,Long foodid) {
		boolean res = true;
		
		String sql = "delete from "+TABLE+" where food_id=?";
		res = res&(getTemplateMgr().getWriteTp().update(sql, new Object[]{foodid})>0);
		res = res&this.newTags(tags);
		return res;
	}

	@Override
	public boolean deleteTags(Long foodid) {
		String sql = "delete from "+TABLE+" where food_id=?";
		return getTemplateMgr().getWriteTp().update(sql, new Object[]{foodid})>0;
	}
}
